package com.hancai.barrage.web.interceptors;

import com.hancai.barrage.model.JsonResult;
import com.hancai.barrage.utils.TokenManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author 涵菜
 * @version 1.0
 * springMVC的拦截器用于拦截控制器方法的执行，
 * 拦截器里面的/*指的是拦截一层目录的请求，/**拦截所有目录的请求
 * preHandle（true放行，false拦截不调用控制器方法）-控制器方法执行之前执行
 * postHandle()控制器方法执行之后执行
 * afterCompletion():处理完MODEL AND VIEW 渲染视图完毕之后执行
 *
 * 通过token从map集合中获取用户登录信息，能获取到说明登录成功，否则登陆失败
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(TokenManager.TOKEN_NAME);
        if(StringUtils.hasText(token)&&TokenManager.getInfo(token)!=null){
           //如果有登录就放行
            return true;
        }
        //响应结果给前端，告诉前端当前没有登陆，响应401状态码
        JsonResult<Object> result = JsonResult.failed(401, "用户尚未登录，请登陆后访问");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(result.getCode()+result.getMsg());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
